package cc.vv.baselibrary.util.download

import android.content.Context
import android.os.Environment
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import zlc.season.rxdownload3.RxDownload
import zlc.season.rxdownload3.core.DownloadConfig
import zlc.season.rxdownload3.core.Mission
import zlc.season.rxdownload3.core.Status
import zlc.season.rxdownload3.core.Succeed
import zlc.season.rxdownload3.extension.ApkInstallExtension
import java.util.concurrent.TimeUnit

/**
 * 创建日期：2018/8/30 on 14:33
 * 描述:
 * 作者:zhangzheng 028
 */
object DownloadManager {
    /**
     * 下载初始化
     */
    private fun initDownload(context: Context) {
        var builder = DownloadConfig.Builder.create(context)
                .enableAutoStart(true)              //自动开始下载
                .useHeadMethod(true)    //使用http HEAD方法进行检查
                .setMaxRange(1)       // 每个任务并发的线程数量
                .setRangeDownloadSize(4 * 1000 * 1000) //每个线程下载的大小，单位字节
                .setMaxMission(1)      // 同时下载的任务数量
                .enableDb(true)                             //启用数据库
                .enableService(true)                        //启用Service
                .enableNotification(false)                   //启用Notification
                .addExtension(ApkInstallExtension::class.java)          //添加扩展
        DownloadConfig.init(builder)
    }

    /**
     * 开始下载方法
     */
    fun downloadApk(apkUrl: String, context: Context, dInterface: DownLoadInterface) {
        initDownload(context)
        val dir = Environment.getExternalStorageDirectory().path + "/cc.vv.btpartyjob/files/apk"
        val filename = apkUrl.substring(apkUrl.lastIndexOf("/"), apkUrl.length)
        RxDownload.create(Mission(apkUrl, filename, dir))
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError {
                    dInterface.downLoadError(it)
                }
                .subscribe { status ->
                    if (status is Succeed) {
                        //开始安装
                        Observable.timer(20, TimeUnit.MICROSECONDS)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe {
                                    RxDownload.extension(apkUrl, ApkInstallExtension::class.java).subscribe()
                                }
                    } else {
                        //下载监听
                        dInterface.downLoadStatus(status)
                    }
                }
        RxDownload.start(apkUrl).subscribe()
    }

    /**
     * 下载监听
     */
    interface DownLoadInterface {
        //下载状态
        fun downLoadStatus(status: Status)

        fun downLoadError(error: Any)
    }

}